import { onMounted, Ref } from 'vue'
import Sortable from 'sortablejs'

export function sortTable(tableData: any, dropCol?: Ref) {
  // 生命周期
  onMounted(() => {
    rowDrop()
    columnDrop()
  })

  // 行拖拽
  const rowDrop = () => {
    const tbody = document.querySelector('.el-table__body-wrapper tbody')
    if (tbody) {
      Sortable.create(tbody as HTMLElement, {
        onEnd({ newIndex, oldIndex }) {
          let currRow
          if (oldIndex !== undefined && newIndex !== undefined) {
            if (!tableData.value) {
              currRow = tableData.splice(oldIndex, 1)[0]
              tableData.splice(newIndex, 0, currRow)
            } else {
              currRow = tableData.value.splice(oldIndex, 1)[0]
              tableData.value.splice(newIndex, 0, currRow)
            }
          }
        }
      })
    }
  }

  // 列拖拽
  const columnDrop = () => {
    const wrapperTr = document.querySelector('.el-table__header-wrapper tr')
    if (wrapperTr) {
      Sortable.create(wrapperTr as HTMLElement, {
        animation: 180,
        delay: 0,
        onEnd: (evt) => {
          if (dropCol?.value?.length) {
            const oldItem = dropCol.value[evt.oldIndex ?? 0]
            dropCol.value.splice(evt.oldIndex ?? 0, 1)
            dropCol.value.splice(evt.newIndex ?? 0, 0, oldItem)
          }
        }
      })
    }
  }
}
